<template>
  <div class="container" :class="{ 'fullscreen-mode': isFullscreen }">
    <div class="top">
      <ps-header :title="title" :showDecoration5="false">
        <template #header>
          <select
            class="chart-select"
            v-model="active"
            @change="loadData"
            v-if="!isFullscreen"
          >
            <option :value="''">全部</option>
            <option
              v-for="item in options"
              :key="item.Udef1"
              :value="item.Udef1"
            >
              {{ item.Udef1 }}
            </option>
          </select>

          <select
            class="chart-select"
            v-model="activeLineID"
            @change="loadData"
            v-if="!isFullscreen"
          >
            <option :value="''">全部</option>
            <option
              v-for="item in lineList"
              :key="item.value"
              :value="item.value"
            >
              {{ item.LineName }}
            </option>
          </select>
        </template>
      </ps-header>

      <div class="tools">
        <div class="right">
          <span>本页共{{ total }}条数据</span>
        </div>
      </div>
    </div>

    <div class="productionPanel3-content">
      <div class="dashboard-row">
        <div class="widget-group">
          <div class="widget-item top-widget">
            <productionBoard17 :key="key" :gxmc="active" :scdw="activeLineID" />
          </div>
          <div class="widget-item bottom-widget">
            <purchaseBoard7 :key="key" />
          </div>
        </div>
        <ps-borderbox6 class="main-table">
          <dv-scroll-board :key="key" :config="config" />
        </ps-borderbox6>
      </div>
      <div class="dashboard-row bottom-row">
        <productionBoard18
          :key="key"
          class="full-widget"
          :activeLineID="activeLineID"
          :active="active"
        />
        <productionBoard19
          :key="key"
          class="full-widget"
          :activeLineID="activeLineID"
          :active="active"
        />
        <productionBoard10
          :key="key"
          class="full-widget"
          :activeLineID="activeLineID"
          :active="active"
        />
      </div>
    </div>
  </div>
</template>

<script setup name="ProcessClassNow">
import { getdscdlkbNow, getgxdlxxNow } from "@/api/processClassNow.js";
import { ref, onMounted, computed, reactive, onUnmounted, inject } from "vue";
import { userStore as useUserStore } from "@/pinia/user";
import { getAllMachine } from "@/api/pannel/machinePannel.js";
import { formatMoney } from "@/utils/globalMethod";
import { useLocalStorage } from "@vueuse/core";
import { storeToRefs } from "pinia";
import { prdPrdLineApi } from "@/api/globalApi";
import productionBoard17 from "@/views/visual/modules/productionBoard17.vue";
import purchaseBoard7 from "@/views/visual/modules/purchaseBoard7.vue";
import productionBoard18 from "@/views/visual/modules/productionBoard18.vue";
import productionBoard19 from "@/views/visual/modules/productionBoard19.vue";
import productionBoard10 from "@/views/visual/modules/productionBoard10.vue";
import moment from "moment";
const updateTime = ref("");
const timer = ref();
const key = ref(0);

const time = ref(300);
const total = ref();
const scrollBoardRef = ref();
const options = ref([]);
const lineList = ref([]);
const socket = inject("socket");
const userStore = useUserStore();
const { profile } = storeToRefs(userStore);
const isFullscreen = inject("isFullScreen");
const active = useLocalStorage("processClassNow.active", "");
const activeLineID = useLocalStorage("processClassNow.activeLineID", "");

// 自动更新时间五分钟
const updateData = () => {
  timer.value = setInterval(() => {
    if (time.value > 0) {
      time.value--;
      const duration = moment.duration(time.value * 1000); // 转换为毫秒
      const minutes = duration.asMinutes(); // 总分钟数（包含小数部分）
      const wholeMinutes = Math.floor(minutes); // 取整得到分钟数
      const remainingSeconds = Math.round((minutes - wholeMinutes) * 60); // 计算剩余的秒数
      updateTime.value = `${wholeMinutes}分${remainingSeconds}秒`;
    } else {
      time.value = 300;
      key.value++;
    }
  }, 1000);
};
const config = reactive({
  data: [],
  header: [
    "行",
    "工单单号",
    "产品名称",
    "规格型号",
    "工单总数",
    "累计良品",
    "待生产数量",
    "不良率",
    "生产状态",
  ],
  headerBGC: "rgba(0,0,0,0)",
  oddRowBGC: "rgba(0,0,0,0)",
  evenRowBGC: "rgba(0,0,0,0)",
  align: [
    "center",
    "center",
    "center",
    "center",
    "center",
    "center",
    "center",
    "center",
    "center",
  ],
  columnWidth: [80, 200, 200, 200, 180, 180, 180, 150, 180],
  rowNum: 15,
  index: false,
  carousel: "page",
  waitTime: 1000 * 20,
});

// 动态控制标题内容
const title = computed(() =>
  active.value
    ? profile.value.company + "-" + active.value
    : profile.value.company
);

/**
 * @description: 渲染滚动的数据
 * @param {*} data
 */
const renderScrollData = (data) => {
  const result = data.map((item, index) => {
    item.Quantity = formatMoney(null, item.Quantity);
    item.GoodQty = formatMoney(null, item.GoodQty);
    item.BadQty = formatMoney(null, item.BadQty);
    item.dscsl = formatMoney(null, item.dscsl);
    return [
      index + 1,
      item.MkNo,
      item.ProdName,
      item.ProdSize,
      item.Quantity,
      item.GoodQty,
      item.dscsl,
      item.BadQty == 0
        ? "0%"
        : ((item.BadQty / item.Quantity) * 100).toFixed(0) + "%",
      `<div class="progress-bar"><div class="progress" style="width: ${
        Number(item.Quantity.replace(/,/g, "") ?? 0) ==
        Number(item.dscsl.replace(/,/g, "") ?? 0)
          ? 0
          : (
              (Number(item.dscsl.replace(/,/g, "") ?? 0) /
                Number(item.Quantity.replace(/,/g, "") ?? 0)) *
              100
            ).toFixed(2)
      }%"></div><div class="text">${
        Number(item.Quantity.replace(/,/g, "") ?? 0) ==
        Number(item.dscsl.replace(/,/g, "") ?? 0)
          ? 0
          : (
              (Number(item.dscsl.replace(/,/g, "") ?? 0) /
                Number(item.Quantity.replace(/,/g, "") ?? 0)) *
              100
            ).toFixed(2)
      }%</div></div>`,
    ];
  });

  if (config.data.length > 0 && scrollBoardRef.value) {
    scrollBoardRef.value.updateRows(result);
  } else {
    config.data = result;
  }
};
/**
 * @description: 加载数据
 */
const loadData = async () => {
  const dscdlkbNow = await getdscdlkbNow({
    gx: active.value,
    lineID: activeLineID.value,
  });
  renderScrollData(dscdlkbNow.data);
  total.value = dscdlkbNow.total;
};

const loadLineList = async () => {
  const { data } = await prdPrdLineApi();
  lineList.value = data;
};

/**
 * @description: 加载工序大类选项
 */
const loadProcessOptions = async () => {
  const { data } = await getgxdlxxNow();
  options.value = data;
};

const keyResize = () => {
  key.value++;
};

onMounted(() => {
  window.addEventListener("fullscreenchange", keyResize);
});

onUnmounted(() => {
  window.removeEventListener("fullscreenchange", keyResize);
});

onMounted(loadProcessOptions);
onMounted(loadData);
onMounted(loadLineList);
onMounted(() => {
  socket.receiveMessage("report-system-update", async (data) => {
    const machine = await getAllMachine({ lineID: active.value });
    renderMachineData(machine.machines);

    const dscdlkbNow = await getdscdlkbNow({
      gx: active.value,
      lineID: activeLineID.value,
    });
    renderScrollData(dscdlkbNow.data);
    total.value = dscdlkbNow.total;
  });
});

onUnmounted(() => {
  socket.removeAllListeners("report-system-update");
});
onMounted(updateData);
onUnmounted(() => {
  timer.value && clearInterval(timer.value);
});
</script>

<style scoped lang="scss">
.container {
  height: 100%;
  background-image: url("../../assets/image/visualization-bg.png");
  display: flex;
  flex-direction: column;

  .top {
    .tools {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .left {
        flex: 1;

        :deep(.el-button:hover) {
          background-color: #ffa500;
          border-color: #ffa500;
        }
      }

      .right {
        color: #fff;
        font-size: 18px;
        font-weight: bold;
        margin-left: auto;
        margin-right: 30px;
      }
    }
  }
}

:deep(.dv-scroll-board .rows .row-item) {
  font-size: 20px;
  letter-spacing: 0px;
}

:deep(.dv-scroll-board .header .header-item) {
  font-size: 20px;
  letter-spacing: 0px;
}

:deep .progress-bar {
  position: relative; /* 定位基准 */
  width: 100%;
  height: 10px;
  background-color: #2d3d4d; /* 背景色（未完成部分的颜色） */
  border-radius: 10px;
  overflow: hidden;
  margin-top: 2%;
}

:deep .progress {
  position: absolute; /* 绝对定位，从左侧开始填充 */
  left: 0; /* 强制从左侧开始 */
  top: 0;
  height: 100%;
  background: linear-gradient(to right, #4fd2dd, #00f2fe); /* 从左到右渐变 */
  z-index: 1; /* 确保在文字下方 */
  transition: width 0.3s; /* 可选：添加过渡动画 */
}

:deep .text {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  color: #ffffff;
  font-size: 12px;
  z-index: 2; /* 确保文字在顶部 */
  pointer-events: none; /* 防止文字拦截点击事件 */
}
.productionPanel3-content {
  height: calc(100vh - 200px); /* 根据顶部栏高度调整 */
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 15px;
}

/* 行布局 */
.dashboard-row {
  display: grid;
  gap: 15px;
  flex: 1;
}

/* 第一行布局 */
.dashboard-row:first-child {
  grid-template-columns: 1fr 4fr; /* 窄组件:主表格 = 1:4 */
  min-height: 45vh;
}

/* 组件容器 */
.widget-group {
  display: grid;
  grid-template-rows: 1fr 1fr; /* 上下等分 */
  gap: 15px;
}

/* 主表格样式 */
.main-table {
  border-radius: 8px;
  overflow: hidden;
}

/* 底部行布局 */
.bottom-row {
  grid-template-columns: repeat(3, 1fr); /* 三列等宽 */
}

/* 通用组件样式 */
.widget-item,
.full-widget {
  border-radius: 6px;
  overflow: hidden;
}

/* 响应式适配 */
@media (max-width: 1600px) {
  .dashboard-row:first-child {
    grid-template-columns: 1fr 1.8fr;
  }

  .bottom-row {
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  }
}

@media (max-width: 1366px) {
  .dashboard-row:first-child {
    grid-template-columns: 1fr 1.5fr;
  }

  .widget-group {
    grid-template-rows: 1.2fr 1fr;
  }
}
</style>
